var table;
var action;

function mostrarJSON(data){
/*Mostrar el JSON que nos devuelve campus-cloud-server-rb*/
        
        //Borramos el contenedor central para mostrar los datos.
        $('#container').empty();
        
        //Variable en la almacenaremos el codigo html que se insertara al en el contenedor central
        var html='';
                
        //Comprobamos si la BD nos ha devuelto una consulta vacia
        if(!$.isEmptyObject(data)){
        	html+= '<table id="table_id">';
			switch (table){
				case 'students':
					switch (action){
						case 'list':
							html+='<thead>';
							html+='<tr>';
							html+='<th>ID</th>';
							html+='<th>NAME</th>';
							html+='</tr>';
							html+='</thead>'
							
							//Recorremos el JSON objeto por objeto
							$.each(data, function(key, val) {
								html+='<tr>';
								html+= '<td>'+ val.id +'</td>';
								html+= '<td>'+ val.surname+', '+val.name +'</td>';
								html+='</tr>';
							});
							html+='</tbody>';
							html+= '</table>';
						break;

						case 'delete':
							html+='<thead>';
							html+='<tr>';
							html+='<th></th>';				
							html+='<th>ID</th>';
							html+='<th>NAME</th>';
							html+='</tr>';
							html+='</thead>'
							
							//Recorremos el JSON objeto por objeto
							$.each(data, function(key, val) {
								html+='<tr>';
								html+= '<td><input type="checkbox" name="chk" value="'+val.id+'"/></td>';
								html+= '<td>'+ val.id +'</td>';
								html+= '<td>'+ val.surname+', '+val.name +'</td>';
								html+='</tr>';
							});
							html+='</tbody>';
							html+= '</table>';
							html+='<br><input type="button" id="deleteButton" class="button" value="Delete Student" onClick="deleteMethod()"/>';
						break;					
					}					
				break;

				case 'teachers':
					switch (action){
						case 'list':
							html+='<thead>';
							html+='<tr>';
							html+='<th>ID</th>';
							html+='<th>NAME</th>';
							html+='</tr>';
							html+='</thead>'
							
							//Recorremos el JSON objeto por objeto
							$.each(data, function(key, val) {
								html+='<tr>';
								html+= '<td>'+ val.id +'</td>';
								html+= '<td>'+ val.surname+', '+val.name +'</td>';
								html+='</tr>';
							});
							html+='</tbody>';
							html+= '</table>';
						break;

						case 'delete':
							html+='<thead>';
							html+='<tr>';
							html+='<th></th>';				
							html+='<th>ID</th>';
							html+='<th>NAME</th>';
							html+='</tr>';
							html+='</thead>'
							
							//Recorremos el JSON objeto por objeto
							$.each(data, function(key, val) {
								html+='<tr>';
								html+= '<td><input type="checkbox" name="chk" value="'+val.id+'"/></td>';
								html+= '<td>'+ val.id +'</td>';
								html+= '<td>'+ val.surname+', '+val.name +'</td>';
								html+='</tr>';
							});
							html+='</tbody>';
							html+= '</table>';
							html+='<br><input type="button" id="deleteButton" class="button" value="Delete Teacher" onClick="deleteMethod()"/>';
						break;					
					}					
				break;

				case 'templates':
					switch (action){
						case 'list':
							html+='<thead>';
							html+='<tr>';
							html+='<th>NAME</th>';
							html+='<th>DESCRIPTION</th>';
							html+='</tr>';
							html+='</thead>'
							
							//Recorremos el JSON objeto por objeto
							$.each(data, function(key, val) {
								html+='<tr>';
								html+= '<td>'+ val.template_name +'</td>';
								html+= '<td>'+ val.template_description +'</td>';
								html+='</tr>';
							});
							html+='</tbody>';
							html+= '</table>';
						break;

						case 'delete':
							html+='<thead>';
							html+='<tr>';
							html+='<th></th>';				
							html+='<th>NAME</th>';
							html+='<th>DESCRIPTION</th>';
							html+='</tr>';
							html+='</thead>'
							
							//Recorremos el JSON objeto por objeto
							$.each(data, function(key, val) {
								html+='<tr>';
								html+= '<td><input type="checkbox" name="chk" value="'+val.id+'"/></td>';
								html+= '<td>'+ val.template_name +'</td>';
								html+= '<td>'+ val.template_description +'</td>';
								html+='</tr>';
							});
							html+='</tbody>';
							html+= '</table>';
							html+='<br><input type="button" id="deleteButton" class="button" value="Delete Template" onClick="deleteMethod()"/>';
						break;					
					}					
				break;

				case 'labs':
					switch (action){
						case 'list':
							html+='<thead>';
								html+='<tr>';
									html+='<th>NAME</th>';
									html+='<th>GROUP</th>';
									html+='<th>LAB DESCRIPTION</th>';
									html+='<th>TEMPLATE DESCRIPTION</th>';
									html+='<th>TEACHER</th>';
								html+='</tr>';
							html+='</thead>';
							html+='<tbody>';
				
							//Recorremos el JSON objeto por objeto
							$.each(data, function(key, val) {
								html+='<tr>';
								html+= '<td>'+ val.lab_name +'</td>';
								html+= '<td>'+ val.lab_group +'</td>';
								html+= '<td>'+ val.lab_description +'</td>';
								html+= '<td>'+ val.template_description +'</td>';
								html+= '<td>'+ val.surname+', '+val.name +'</td>';
								html+='</tr>';
							});
							html+='</tbody>';
							html+= '</table>';
						break;
				
						case 'create':
							html+='<thead>';
								html+='<tr>';
									html+='<th></th>';
									html+='<th>NAME</th>';
									html+='<th>TEMPLATE DESCRIPTION</th>';
							
								html+='</tr>';
							html+='</thead>';
							html+='<tbody>';
				
							//Recorremos el JSON objeto por objeto
							$.each(data, function(key, val) {
								html+='<tr>';
								html+= '<td><input type="checkbox" name="chk" value="'+val.id+'"/></td>';
								html+= '<td>'+ val.template_name +'</td>';
								html+= '<td>'+ val.template_description +'</td>';
								html+='</tr>';
							});
							html+='</tbody>';
							html+= '</table>';
							html+='<br><input type="button" id="createButton" class="button" value="Create Lab" onClick="createLab()"/>';
						break;
				
						case 'delete':
							html+='<thead>';
								html+='<tr>';
									html+='<th></th>';
									html+='<th>NAME</th>';
									html+='<th>GROUP</th>';
									html+='<th>LAB DESCRIPTION</th>';
									html+='<th>TEMPLATE DESCRIPTION</th>';
									html+='<th>TEACHER</th>';
								html+='</tr>';
							html+='</thead>';
							html+='<tbody>';
				
							//Recorremos el JSON objeto por objeto
							$.each(data, function(key, val) {
								html+='<tr>';
								html+= '<td><input type="checkbox" name="chk" value="'+val.lab_id+'"/></td>';
								html+= '<td>'+ val.lab_name +'</td>';
								html+= '<td>'+ val.lab_group +'</td>';
								html+= '<td>'+ val.lab_description +'</td>';
								html+= '<td>'+ val.template_description +'</td>';
								html+= '<td>'+ val.surname+', '+val.name +'</td>';
								html+='</tr>';
							});
							html+='</tbody>';
							html+= '</table>';
							html+='<br><input type="button" id="deleteButton" class="button" value="Delete Lab" onClick="deleteMethod()"/>';
						break;					
					}					
				break;
		}				
        }

        //Si nuestra consulta nos ha devuelto un JSON vacio (es decir, nil) mostramos un aviso
        else{ 
                html+= 'The are no data to show';
        }
                        
        //Insertamos en el contenedor central el codigo html definitivo que hemos generado tras analizar el JSON devuelto en la consulta
        $('#container').append(html);
	$('#table_id').dataTable({
		"bPaginate": false,
		"bInfo": false,
		"bSort": true,
		"bSortClasses": false	
	});
}
function nif(dni) {
  	numero = dni.substr(0,dni.length-1);
  	let = dni.substr(dni.length-1,1);
  	numero = numero % 23;
  	letra='TRWAGMYFPDXBNJZSQVHLCKET';
  	letra=letra.substring(numero,numero+1);
  	if (letra!=let) 
    		return true;
	return false;
}
function createST(){
	$("#container").empty();
	var html = '<div id="create">'
	html+='<form id="createForm">';
	html+='<br>';
	html+='<table>';
	html+='<tbody>';
	html+='<tr>';
	html+='<td align="right"><b>NIF:</b></td>';
	html+='<td align="left"><input type="text" size="9" name="NIF" id="NIF"/><br></td>';
	html+='</tr>';
	html+='<tr>';
	html+='<td align="right"><b>Name:</b></td>';
	html+='<td align="left"><input type="text" size="15" name="name" id="name"/><br></td>';
	html+='</tr>';
	html+='<tr>';
	html+='<td align="right"><b>Surname:</b></td>';
	html+='<td align="left"><input type="text" size="20" name="surname" id="surname"/><br></td>';
	html+='</tr>';
	html+='<tr>';
	html+='<td colspan="2" align="center"><input type="button" class="button" id="buttonForm" value="Create!"/></td>';
	html+='</tr>';
	html+='</tbody>';
	html+='</table>';
	html+='</form>';
	html+='</div>';
	
	$('#container').append(html);
	$('#buttonForm').click(function () {
		create();
	});

}

function create(){
	var pID = $("#NIF").val();
	var pName = $("#name").val();
	var pSurname = $("#surname").val();
	/*if (nif(pID))
		alert("Invalid NIF");
	else*/ if (pName=="" || pSurname=="")
		alert("Name or Surname are empty");
	else{
		$.ajax({
                url: "/administrators/"+table+"/create",
		type:"POST",
		data:{ID: pID, name: pName, surname: pSurname},
                success: function(){
			var html3='<div id="createDialog" title="Congratulations"> The '+table.substr(0,table.length-1)+' has been created successfully</div>';
			$('#container').append(html3);
			$('#createDialog').dialog({
   				close: function() {
					action = "list";   
					pedirJSON();
					}
			});	
		},
                error: function(response){
			var html3='<div id="createDialog" title="Sorry">'+response.responseText+'</div>';
			$('#container').append(html3);
			$('#createDialog').dialog({
   				close: createST()
				});	
		}
            	});	
	}
}

function createLab(){

	if ($(":checkbox").filter(":checked").length>1){
		alert("Only one template can be checked !");
	}
	else if ($(":checkbox").filter(":checked").length<1){
		alert("Please, check one template");
	}
	else{
		var templateID = $(":checkbox").filter(":checked").val();
		var html2 = '<div id="create">'
				
		html2+='<form id="createForm">';
		html2+='<br>';
                html2+='<table>';
		html2+='<tbody>';
		html2+='<tr>';
		html2+='<td align="right"><b>Teacher NIF:</b></td>';
		html2+='<td align="left"><input type="text" size="9" name="teacherNIF" id="teacherNIF"/><br></td>';
		html2+='</tr>';
		html2+='<tr>';
		html2+='<td align="right"><b>Lab name:</b></td>';
		html2+='<td align="left"><input type="text" size="15" name="labName" id="labName"/><br></td>';
		html2+='</tr>';
		html2+='<tr>';
		html2+='<td align="right"><b>Group:</b></td>';
		html2+='<td align="left"><input type="text" size="1" name="labGroup" id="labGroup"/><br></td>';
		html2+='</tr>';
		html2+='<tr>';
		html2+='<td align="right" valign="top"><b>Description: </b></td>';
		html2+='<td align="left"><textarea name="labDescription" id="labDescription" rows="3" cols="20"></textarea></td>';
		html2+='</tr>';
      		html2+='<tr>';
                html2+='<td colspan="2" align="center"><input type="button" class="button" id="labButton" value="Create!"/></td>';
		html2+='</tr>';
		html2+='</tbody>';
		html2+='</table>';
        	html2+='</form>';

		html2+='</div>';
		
		$('#container').append(html2);
		$('#labButton').click(function () {
        		create(templateID);
    		});
	}
}

function create(templateID){
	var tNIF = $("#teacherNIF").val();
	/*if (nif(pID))
		alert("Invalid NIF");
	else*/ if ($("#labName").val().length<2)
		alert("Lab name length must be 2 letters at least");
	else if ($("#labGroup").val().length!=1)
		alert("Lab group must be 1 letter");
	else if ($("#labDescription").val().length<1)
		alert("Lab description is empty.<br><br>Please, enter a description for this lab");
	else{
		var labN = $("#labName").val();
		var labG= $("#labGroup").val();
		var labD = $("#labDescription").val();

		$.ajax({
                url: "/administrators/labs/create",
		type:"POST",
		data:{template: templateID, teacher: tNIF, labName: labN, labGroup: labG, labDescription: labD},
                success: function(){
			var html3='<div id="createDialog" title="Congratulations"> The lab has been created successfully</div>';
			$('#container').append(html3);
			$('#createDialog').dialog({
   				close: function() { 
					action = "list";					
					pedirJSON(); 
					}
				});	
		},
                error: function(){
			var html3='<div id="createDialog" title="Sorry"> An error ocurred when the server tried to create the Lab.<br><br>Review Teacher NIF</div>';
			$('#container').append(html3);
			$('#createDialog').dialog({
   				close: function() {
					action = "create"; 
					pedirJSON(); 
					}
				});	
		}
            	});
	}				
}

function createT(){
	$("#container").empty();
	var html = '<div id="create">'
	html+='<form id="createForm">';
	html+='<br>';
	html+='<table>';
	html+='<tbody>';
	html+='<tr>';
	html+='<td align="right"><b>Name:</b></td>';
	html+='<td align="left"><input type="text" size="15" name="name" id="name"/><br></td>';
	html+='</tr>';
	html+='<tr>';
	html+='<td align="right" valign="top"><b>Description: </b></td>';
	html+='<td align="left"><textarea name="templateDescription" id="templateDescription" rows="3" cols="20"></textarea></td>';
	html+='</tr>';
	html+='<tr>';
	html+='<td align="right"><b>URI:</b></td>';
	html+='<td align="left"><input type="text" size="30" name="templateURI" id="templateURI"/><br></td>';
	html+='</tr>';
	html+='<tr>';
	html+='<td colspan="2" align="center"><input type="button" class="button" id="buttonForm" value="Create"/></td>';
	html+='</tr>';
	html+='</tbody>';
	html+='</table>';
	html+='</form>';
	html+='</div>';
	
	$('#container').append(html);
	$('#buttonForm').click(function () {
		createTT();
	});	
}

function createTT(){
	var pName = $("#name").val();
	var pDescription = $("#templateDescription").val();
	var pURI = $("#templateURI").val();
	
	if (pName=="") alert("Name is empty!. Please introduce a template name");
	else if (pDescription=="") alert("Description is empty!. Please introduce a template description");
	else if (pURI=="") alert("URI is empty!. Please introduce a template URI");	
	else{
		$.ajax({
                url: "/administrators/templates/create",
		type:"POST",
		data:{name: pName, description: pDescription, URI: pURI},
                success: function(){
			var html3='<div id="createDialog" title="Congratulations"> The '+table.substr(0,table.length-1)+' has been created successfully</div>';
			$('#container').append(html3);
			$('#createDialog').dialog({
   				close: function() {
					action = "list";   
					pedirJSON();
					}
			});	
		},
                error: function(response){
			var html3='<div id="createDialog" title="Sorry">'+response.responseText+'</div>';
			$('#container').append(html3);
			$('#createDialog').dialog({
   				close: createT()
				});	
		}
            	});	
	}

}

function deleteMethod(){
	if ($(":checkbox").filter(":checked").length>1){
		alert('Only one '+table.substr(0,table.length-1)+' can be deleted !');
	}
	else if ($(":checkbox").filter(":checked").length<1){
		alert('Please, check one '+table.substr(0,table.length-1));
	}
	else{
		var pID = $(":checkbox").filter(":checked").val();
		
		$.ajax({
                url: "/administrators/"+table+"/delete",
		type:"POST",
		data:{ID: pID},
                success: function(){
			var html3='<div id="deleteDialog" title="Congratulations"> The '+table.substr(0,table.length-1)+' has been deleted successfully</div>';
			$('#container').append(html3);
			$('#deleteDialog').dialog({
   				close: function() { 
					action = "list";  
					pedirJSON();					
					}
				});	
		},
                error: function(response){
			var html3='<div id="deleteDialog" title="Sorry">'+response.responseText+'</div>';
			$('#container').append(html3);
			$('#deleteDialog').dialog({
   				close: function() { 
					action = "delete";  
					pedirJSON();
					}
				});	
		}
            	});
	}
}

function pedirJSON(){
/* aqui estamos intentando hacer una peticion al servidor campus-cloud-server.rb para que nos de el JSON*/
            $.ajax({
                url: "/administrators/"+table+"/"+action,
		type:"GET",
		dataType: 'json',
                success: mostrarJSON,
                error: mostrarJSON
            });
}

function logout(){
	$.ajax({
                url: "/logout",
		type:"POST",
                success: showindex,
                error: function(){
			alert("error");
		}
            });	
}

function showindex(){
	window.location.href="/";
}

/* Aqui estamos diciendo mediante las funciones que nos permite la libreria jQuery ($) que al elemento con id login_btn cuando le hagamos click ejecute la funcion pedirJSON*/
$(document).ready(function(){
    
	$("#li_student").click(function () {
      
   	});
    	$("#li_student_list").click(function () {
		table = "students";
		action = "list";        	
		pedirJSON();
    	});
    	$("#li_student_create").click(function () {
		table = "students"; 		
		action = "create";        	
		createST();
    	});
    	$("#li_student_delete").click(function () {
        	table = "students";
		action = "delete";		
		pedirJSON();
    	});
	


	$("#li_teacher").click(function () {
      
   	});
    	$("#li_teacher_list").click(function () {
		table = "teachers";
		action = "list";        	
		pedirJSON();
    	});
    	$("#li_teacher_create").click(function () {
		table = "teachers"; 		
		action = "create";        	
		createST();
    	});
    	$("#li_teacher_delete").click(function () {
        	table = "teachers";
		action = "delete";		
		pedirJSON();
    	});

	
	
	$("#li_template").click(function () {
      
   	});
    	$("#li_template_list").click(function () {
		table = "templates";
		action = "list";        	
		pedirJSON();
    	});
    	$("#li_template_create").click(function () {
		table = "templates"; 		
		action = "create";        	
		createT();
    	});
    	$("#li_template_delete").click(function () {
        	table = "templates";
		action = "delete";		
		pedirJSON();
    	});



	$("#li_lab").click(function () {
      
   	});
    	$("#li_lab_list").click(function () {
		table = "labs";
		action = "list";        	
		pedirJSON();
    	});
    	$("#li_lab_create").click(function () {
		table = "labs"; 		
		action = "create";        	
		pedirJSON();
    	});
    	$("#li_lab_delete").click(function () {
        	table = "labs";
		action = "delete";		
		pedirJSON();
    	});






/*$("#link-Students").click(function () {
	pedirJSON("students");
	table = "students";
    });     
    $("#link-Teachers").click(function () {
        pedirJSON("teachers");
	table = "teachers";
    });
    $("#link-Templates").click(function () {
        pedirJSON("templates");
	table = "templates";
    });
    $("#link-Labs").click(function () {
        pedirJSON("labs");
	table = "labs";
    });
    $("#link-Sugerencias").click(function () {
        pedirJSON("sugerencias");
	table = "sugerencias";
    });*/
    $("#logout").click(function () {
        logout();
    });
});
